package tags;

import DAO.DbDao;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import java.io.IOException;
import java.sql.ResultSet;

/**
 * Created by hadoop on 17-6-14.
 * 带属性的自定义标签类：查询数据库
 */
public class QueryTag extends SimpleTagSupport{
    private String driver;
    private String url;
    private String user;
    private String pass;
    private String sql;
    @Override
    public void doTag() throws JspException, IOException {
        DbDao dao = new DbDao(driver,url,user,pass);
        try {
            ResultSet rs = dao.query(sql);
            int colCount = rs.getMetaData().getColumnCount();
            JspWriter out = getJspContext().getOut();
            out.write("<table border='1' width='400'>");
            while(rs.next()){
                out.write("<tr>");
                for(int i=1;i<=colCount;i++){
                    out.write("<td>");
                    out.write(rs.getString(i));
                    out.write("</td>");
                }
                out.write("</tr>");
            }
            out.write("</table>");
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                dao.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }

    //getter and setter

    public String getDriver() {
        return driver;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUser() {
        return user;
    }

    public void setUser(String user) {
        this.user = user;
    }

    public String getPass() {
        return pass;
    }

    public void setPass(String pass) {
        this.pass = pass;
    }

    public String getSql() {
        return sql;
    }

    public void setSql(String sql) {
        this.sql = sql;
    }

}
